package com.yuandian.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.management.entity.ConfComponentResource;
import com.yuandian.api.management.entity.ConfConfirmedUrl;
import com.yuandian.api.management.entity.ConfUnconfirmedUrl;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.mapper.ConfComponentResourceMapper;
import com.yuandian.management.service.ConfComponentResourceService;
import com.yuandian.management.service.ConfConfirmedUrlService;
import com.yuandian.management.service.ConfUnconfirmedUrlService;
import com.yuandian.management.vo.UnconfirmedResourceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 组件资源配置表-Service实现
 * @author zfsn
 * @date 2023-3-17
 */
@Service
public class ConfComponentResourceServiceImpl extends ServiceImpl<ConfComponentResourceMapper, ConfComponentResource>
		implements ConfComponentResourceService {

	@Autowired
	ConfComponentResourceMapper componentResourceMapper;

	@Autowired
	private ConfUnconfirmedUrlService confUnconfirmedUrlService;

	@Autowired
	private ConfConfirmedUrlService confConfirmedUrlService;

	@Override
	public void resetIpFilter() {
		componentResourceMapper.resetIpFilter();
	}

	/**
	 * 分页查询
	 *
	 * @param confComponentResource 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfComponentResource> listPage(ConfComponentResource confComponentResource) {
		return componentResourceMapper.listPage(new Page<>(confComponentResource.getPageNum(), confComponentResource.getPageSize()), confComponentResource);
	}

	/**
	 * 新增数据
	 *
	 * @param confComponentResource 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R<String> saveData(ConfComponentResource confComponentResource) {

		// 1、判断同系统、同网端是否存在相同的服务资源，已经存在则不进行新增
		LambdaQueryWrapper<ConfComponentResource> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(ConfComponentResource::getSystemId, confComponentResource.getSystemId());
		queryWrapper.eq(ConfComponentResource::getSegmentId, confComponentResource.getSegmentId());
		queryWrapper.eq(ConfComponentResource::getIdentifyStr, confComponentResource.getIdentifyStr());
		if (super.count(queryWrapper) > 0) {
			return R.failed("IT端组件服务资源已存在");
		}

		// 2、检查同系统中是否存在以编辑后的url为前缀的服务资源(子字符串)，若存在提示"该服务资源已存在于**系统、**网端上"
		Integer count = componentResourceMapper.checkConfirmedUrlInCsr(confComponentResource);
		if (count > 0) {
//			ConfComponentResource tempCsr = csrList.get(0);
//			List<SearchOptionVo> systemCodes = searchOptionService.queryDefaultAppSystemOptions(new SearchParams());
//			String systemCodeName = "";
//			for (SearchOptionVo systemCode : systemCodes) {
//				if (tempCsr.getSystemCode().equals(systemCode.getCode())) {
//					systemCodeName = systemCode.getLabel();
//					break;
//				}
//			}
//			String segmentName = "";
//			List<SearchOptionVo> segments = searchOptionService.querySegmentBySystemCode(system.getResourceCoding());
//			for (SearchOptionVo segment : segments) {
//				if (String.valueOf(tempCsr.getSystemItId()).equals(segment.getId())) {
//					segmentName = segment.getLabel();
//					break;
//				}
//			}

			return R.failed("确认失败, 该系统已存在改资源编码");
		}

		// 3、新增IT路径组件服务资源
		confComponentResource.setCreateBy(SecurityUtils.getUser().getName());
		confComponentResource.setCreateTime(LocalDateTime.now());
		confComponentResource.setIsDel(0);
		confComponentResource.setIdentifyType(1);
		confComponentResource.setSystemId(confComponentResource.getSystemId());
		super.save(confComponentResource);

		// 4、查询符合条件的未确认服务资源
		List<ConfUnconfirmedUrl> urList = new ArrayList<>();
		UnconfirmedResourceVo urv = new UnconfirmedResourceVo();
		// 4.1、编辑后的IT路径组件服务资源url精确匹配未确认服务资源原始url
		urv.setOriginalUrlExact(confComponentResource.getIdentifyStr());
		urList.addAll(confUnconfirmedUrlService.queryListByCondition(urv));
		// 4.2、编辑后的IT路径组件服务资源url加上"/"号后向右模糊匹配未确认服务资源原始url
		urv.setOriginalUrlExact(null);
		urv.setOriginalUrl(confComponentResource.getIdentifyStr() + "/");
		urList.addAll(confUnconfirmedUrlService.queryListByCondition(urv));

		LambdaQueryWrapper<ConfConfirmedUrl> confirmedUrlLambdaQueryWrapper = Wrappers.lambdaQuery();
		confirmedUrlLambdaQueryWrapper.eq(ConfConfirmedUrl::getSegmentId, confComponentResource.getSegmentId());
		confirmedUrlLambdaQueryWrapper.eq(ConfConfirmedUrl::getConfirmedUrl, confComponentResource.getIdentifyStr());

		List<ConfConfirmedUrl> list = confConfirmedUrlService.list(confirmedUrlLambdaQueryWrapper);

		if (urList.size() <= 0 && list.size() <= 0) {
			// 新增成功，无自动确认的未确认服务资源，无自动再次确认的已确认服务资源
			// return result.setFail(Result.FAIL,
			// "新增成功，无自动确认的未确认服务资源，无自动再次确认的已确认服务资源");
			return R.ok();
		}
		Integer id = confComponentResource.getId();
		// 6、将未确认服务资源进行确认，移到已确认服务资源表中
		List<Integer> unConfirmedResourceIds = new ArrayList<>();
		List<ConfConfirmedUrl> confirmedResourceList = new ArrayList<>();
		urList.forEach((ur) -> {
			unConfirmedResourceIds.add(ur.getId());
			ConfConfirmedUrl confirmedResource = new ConfConfirmedUrl();
			confirmedResource.setResourceCode(ur.getResourceCode());
			confirmedResource.setPrefixUrl(ur.getPrefixUrl());
			confirmedResource.setOriUrl(ur.getOriUrl());
			confirmedResource.setConfirmedUrl(confComponentResource.getIdentifyStr());
			confirmedResource.setStatus(0); // 0: 前缀URL
			confirmedResource.setSystemId(confComponentResource.getSystemId());
			confirmedResource.setSegmentId(confComponentResource.getSegmentId());
			confirmedResource.setResourceComponentId(id);
			confirmedResourceList.add(confirmedResource);
		});


		if (confirmedResourceList.size() > 0) {
			if (confConfirmedUrlService.saveBatch(confirmedResourceList)) {
				// 写入已确认服务资源表中失败
				return R.failed("写入已确认服务资源表中失败");
			}
		}

		// 8、删除未确认服务资源
		if (unConfirmedResourceIds.size() > 0) {
			if (confUnconfirmedUrlService.removeBatchByIds(unConfirmedResourceIds)) {
				// 删除未确认服务资源失败
				return R.failed("删除未确认服务资源失败");
			}
		}
		return R.ok();
	}

	/**
	 * 通过主键更新数据
	 *
	 * @param confComponentResource 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R<String> updateData(ConfComponentResource confComponentResource) {
		return R.ok();
	}

	@Override
	public R<String> deleteByIds(List<Integer> ids) {
		List<Long> delIds1 = new ArrayList<>();
		for (Integer id : ids) {
			// 1、先查询出这条IT端组件服务资源
			Long csrId = id.longValue();
			ConfComponentResource csr = super.getById(csrId);
			if (csr == null) {
				// IT端组件服务资源不存在
				return R.failed("IT端组件服务资源不存在");
			}
			delIds1.add(csrId);

			// 2、查询对应系统、网端、已确认url一致的已确认服务资源
			LambdaQueryWrapper<ConfConfirmedUrl> confirmedUrlLambdaQueryWrapper = Wrappers.lambdaQuery();
			confirmedUrlLambdaQueryWrapper.eq(ConfConfirmedUrl::getSegmentId, csr.getSegmentId());
			confirmedUrlLambdaQueryWrapper.eq(ConfConfirmedUrl::getConfirmedUrl, csr.getIdentifyStr());
			confirmedUrlLambdaQueryWrapper.eq(ConfConfirmedUrl::getConfirmedUrl, csr.getIdentifyStr());

			List<ConfConfirmedUrl> deleteList = confConfirmedUrlService.list(confirmedUrlLambdaQueryWrapper);


			// 3、更新业务服务资源为未使用，供数据重组重新发现
			List<Integer> delIds2 = new ArrayList<>();
			for (ConfConfirmedUrl cr : deleteList) {
				delIds2.add(cr.getId());
			}

			// 更新业务服务资源为未使用，用IT端服务资源url模糊匹配
			confUnconfirmedUrlService.updateBusinessResourceNoUsed(csr.getIdentifyStr());

			// 4、批量删除已确认服务资源
			if (delIds2.size() > 0) {
				if (confConfirmedUrlService.removeBatchByIds(delIds2)) {
					// 删除已确认服务资源失败
					return R.failed("删除已确认服务资源失败");
				}
			}
		}

		// 5、批量删除IT端组件服务资源
		if (delIds1.size() > 0) {
			if (super.removeByIds(delIds1)) {
				// 删除IT路径组件服务资源失败
				return R.failed("删除IT路径组件服务资源失败");
			}
		}
		return R.ok();
	}

}
